package com.szbmyoubao.app.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.PersistableBundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.szbmyoubao.app.adapter.LazyFragmentPagerAdapter
import com.szbmyoubao.app.ui.main.home.HomeFragment
import com.szbmyoubao.app.ui.main.live.ToolsFragment
import com.szbmyoubao.app.ui.main.mine.MineFragment
import com.szbmyoubao.app.ui.main.rank.RankFragment
import com.szbmyoubao.app.utils.NotificationUtils
import com.szbmyoubao.app.view.dialog.VersionUpdateDialog
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.helper.ClickHelper
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.ActivityMainBinding
import com.permissionx.guolindev.PermissionX


class MainActivity : BaseMvvmActivity<ActivityMainBinding, MainViewModel>(), View.OnClickListener {
    override val userBaseTitle: Boolean
        get() = false

    private val currentPosition: Int by lazy { intent.getIntExtra(PAGE_INDEX, 0) }
    private val fragments: MutableList<Fragment> = mutableListOf()
    private val homeFragment: HomeFragment by lazy { HomeFragment.Companion.newInstance() }
    private val rankFragment: RankFragment by lazy { RankFragment.Companion.newInstance() }
    private val toolsFragment: ToolsFragment by lazy { ToolsFragment.Companion.newInstance() }
    private val mineFragment: MineFragment by lazy { MineFragment.Companion.newInstance() }
    private val tabs: Array<String> by lazy { arrayOf("首页", "排行", "工具", "我的") }
    override fun inflateBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        checkHasNewVersion()
        initTabTitle()
        initViewPager()
        handleBottomTab(currentPosition)

        // 检测通知状态
//        checkNotification()


    }

    private fun initTabTitle() {
        binding.homeTitle.text = tabs[0]
        binding.cartTitle.text = tabs[1]
        binding.mallTitle.text = tabs[2]
        binding.mineTitle.text = tabs[3]
    }

    /**
     * 检测是否开启通知,未开启的时候引导开启
     */
    private fun checkNotification() {

        if (NotificationUtils.Companion.areNotificationsEnabled()) return
        showAlert(content = "为避免错过优质内容，请允许开启手机通知") {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.POST_NOTIFICATIONS
                    ) !== PackageManager.PERMISSION_GRANTED
                ) {
                    PermissionX.init(this).permissions(Manifest.permission.POST_NOTIFICATIONS)
                        .request { allGranted, grantedList, deniedList ->
                            if (!allGranted) {
                                ToastUtils.show("您拒绝了授予接收通知权限！")
                            }
                        }
                } else {
                }
            } else {
                NotificationUtils.Companion.openNotificationSettingsForApp(this)
            }

        }
    }

    override fun initEvent() {
        binding.homeView.setOnClickListener(this)
        binding.mallView.setOnClickListener(this)
        binding.cartView.setOnClickListener(this)
        binding.mineView.setOnClickListener(this)
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is MainState.ShowDialog -> {
                    VersionUpdateDialog(this, it.data).show()
                }

                else -> {}
            }
        }
    }

    /**
     * 检查版本更新
     */
    private fun checkHasNewVersion() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(MainIntent.FetchLastVersion)
        }
    }

    /**
     * 检查版本更新
     */
    fun fetchH5Host() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(MainIntent.FetchH5Host)
        }
    }

    private fun initViewPager() {
        if (fragments.isEmpty()) {
            if (!homeFragment.isAdded) {
                fragments.add(homeFragment)
            }
            if (!rankFragment.isAdded) {
                fragments.add(rankFragment)
            }
            if (!toolsFragment.isAdded) {
                fragments.add(toolsFragment)
            }
            if (!mineFragment.isAdded) {
                fragments.add(mineFragment)
            }
        }
        binding.vpContent.adapter = LazyFragmentPagerAdapter(supportFragmentManager, fragments)
        binding.vpContent.offscreenPageLimit = fragments.size
        binding.vpContent.setCanScroll(false)


    }

    private fun handleBottomTab(index: Int) {
        when (index) {
            0 -> {
                binding.homeIcon.setImageResource(R.mipmap.icon_tab_home_selected)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_rank_default)
                binding.mallIcon.setImageResource(R.mipmap.icon_tab_tools_default)
                binding.mineIcon.setImageResource(R.mipmap.icon_tab_mine_default)
            }

            1 -> {
                binding.homeIcon.setImageResource(R.mipmap.icon_tab_home_default)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_rank_selected)
                binding.mallIcon.setImageResource(R.mipmap.icon_tab_tools_default)
                binding.mineIcon.setImageResource(R.mipmap.icon_tab_mine_default)
            }

            2 -> {
                binding.homeIcon.setImageResource(R.mipmap.icon_tab_home_default)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_rank_default)
                binding.mallIcon.setImageResource(R.mipmap.icon_tab_tools_selected)
                binding.mineIcon.setImageResource(R.mipmap.icon_tab_mine_default)
            }

            3 -> {
                binding.homeIcon.setImageResource(R.mipmap.icon_tab_home_default)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_rank_default)
                binding.mallIcon.setImageResource(R.mipmap.icon_tab_tools_default)
                binding.mineIcon.setImageResource(R.mipmap.icon_tab_mine_selected)
            }

            else -> {}
        }
        binding.homeTitle.isChecked = index == 0
        binding.cartTitle.isChecked = index == 1
        binding.mallTitle.isChecked = index == 2
        binding.mineTitle.isChecked = index == 3
        binding.vpContent.setCurrentItem(index, false)
        binding.vpContent.postDelayed({
            checkHasNewVersion()

        }, 500)
//        if (index==0&&homeFragment.isAdded&&homeFragment.isResumed){
//            homeFragment.showNewerDialog()
//        }
    }

    /**
     * 保存当前显示页面的索引
     */
    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        outState.putInt("currentPosition", currentPosition)
        outState.remove("android:support:fragments")
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        val currentPosition = savedInstanceState.getInt("currentPosition", 0)
        binding.vpContent.setCurrentItem(currentPosition, false)
        handleBottomTab(currentPosition)
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.homeView -> {
                handleBottomTab(0)
            }


            R.id.cartView -> {
                handleBottomTab(1)
            }

            R.id.mallView -> {
                handleBottomTab(2)
            }

            R.id.mineView -> {
                handleBottomTab(3)
            }
        }
    }


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent != null) {
            val pageIndex = intent.getIntExtra(PAGE_INDEX, 0)
            handleBottomTab(pageIndex)
        }

    }

    override fun onBackPressed() {
        if (!ClickHelper.isOnDoubleClick()) {
            ToastUtils.show(getString(R.string.text_click_to_exit))
            return
        }
        super.onBackPressed()
    }

    companion object {
        private const val PAGE_INDEX = "key_page_index"
        fun launch(context: Context, index: Int = 0) {
            context.startActivity(
                Intent(context, MainActivity::class.java).putExtra(
                    PAGE_INDEX,
                    index
                )
            )
        }
    }

}